namespace sgf.server.hotfix
{
    public class NetMgr : BaseMgr
    {
        public override async Task InitSync()
        {
            var port = Config.GetInt("port");
            if (port > 0)
            {
                var tcpServer = new KestrelNetServer();
                await tcpServer.Start(port, OnConnect, OnMessage, OnDisconnect);
            }

            var websocket = Config.GetStr("websocket");
            if (websocket != "")
            {
                var webSocketServer = new WebSocketServer();
                await webSocketServer.Start(websocket, OnConnect, OnMessage, OnDisconnect);
            }

            var httpPort = Config.GetInt("httpPort");
            if (httpPort > 0)
            {
                var httpServer = new HttpServer();
                await httpServer.Start(httpPort, Config.GetBool("useHttps"), OnReceiveHttpMsg);
            }
        }

        private Dictionary<long, Session> GetSessions()
        {
            var netActor = GetBus<NetActor>();
            if (netActor == null) return new Dictionary<long, Session>();
            return netActor.Sessions;
        }

        private void OnConnect(NetChannel netChannel)
        {
            var session = new Session(IDGenerator.NextId(), netChannel, ActorCore.GetPid(typeof(AccountActor)));
            GetSessions().Add(session.sessionId, session);
            netChannel.SetData("sessionId", session.sessionId);
            LogMgr.Debug($"{netChannel.remoteAddress} 连接成功");
        }

        private void OnDisconnect(NetChannel netChannel)
        {
            var sessionId = netChannel.GetData<long>("sessionId");
            GetSessions().Remove(sessionId);
            LogMgr.Debug($"{netChannel.remoteAddress} 断开链接");
        }

        private void OnMessage(long sessionId, byte[] data)
        {
            GetSessions().TryGetValue(sessionId, out var session);
            if (session == null)
            {
                LogMgr.Error($"找不到session {sessionId}");
                return;
            }

            try
            {
                var msg = Message.FromBytes(data);
                ActorCore.Send(session.Pid, msg.GetDataObj());
                LogMgr.Debug($"收到消息 {sessionId} {msg.GetType()}");
            }
            catch (Exception e)
            {
                LogMgr.Error($"消息解析错误 {e.Message}");
            }
        }

        private void OnReceiveHttpMsg(Microsoft.AspNetCore.Http.HttpContext context)
        {
            // context.Request.Path  去掉开头的 /game/
            var pathValue = context.Request.Path.Value;
            if (pathValue == null || pathValue.Length < 6)
            {
                LogMgr.Error($"http请求路径错误 {pathValue}");
                return;
            }

            var path = pathValue[6..];
            HotfixMgr.GetHttpMsgHandler(path)?.Run(busActor, context.Request, context.Response);
        }
    }
}